import React,{ useState, useEffect, useRef, useCallback, useReducer,useMemo, FC } from 'react';
//建立页面数据和store 的关联
import { connect } from 'react-redux'
import { Post, Get, Patch, Put } from '../../utils/utilHttp'
import { Link, RouteComponentProps } from 'react-router-dom';
import { Button, Radio, Checkbox, WhiteSpace, WingBlank,Pagination,Icon } from 'antd-mobile';
import './index.scss'


import Top from '../../components/top/top'

//useState 异步操作 加个监听器 监听是否是新的数据 ,已经是新值 调用setXState 的第二个参数
export const useNewState = (initState:any) => {
  const [state, setState] = useState(initState);
  const ref = useRef();
  const setXState = (newState:any, cb:any) => {
      setState(() => {
      ref.current = cb;
      return newState;
      });
  };
  useEffect(() => {
      if (ref.current) {
        console.log(state);
        (ref.current as any)();
      }
  });
  return [state, setXState];
};


interface IState {
}
interface IProps extends RouteComponentProps {
}
class Myinfo extends React.Component<IProps, IState> {
  render() {
    return (
      <div className='box'>
        <Top history={this.props.history}></Top>
        <div className='title'>React Hook Ts 购物车</div>
        <Cart/>
      </div>
    )
  }
}

//Cart 1.0
// interface Goods {
//   select:boolean,
//   name:string,
//   money:number
// }
// const Cart:React.FC<{}> = (props) => {
//   //复选框
//   const CheckboxItem = Checkbox.CheckboxItem;
//   let [allMoney,setAllMoney] = useState(0);
//   let [allSelect,setAllSelect] = useState(false);
//   let [resDatas,setAllResDatas] =useState<Goods[]>([{select:false,name:'牛奶',money:100},
//   {select:false,name:'面包',money:100},
//   {select:false,name:'咖啡',money:100},
//   {select:false,name:'手机',money:100},
//   {select:false,name:'电脑',money:100},
//   {select:false,name:'妹子',money:100}]);
//   //类似声明 this 保存最新数据
//   let thisUseRef = useRef<Goods[]>(resDatas);

//   useEffect(()=>{
//     thisUseRef.current = resDatas;
//   })
//   //单选
//   const changeCardDatas =(index:number)=>{
//     console.log('单选')
//     let _resDatas = JSON.parse(JSON.stringify(resDatas));
//     _resDatas[index].select = !_resDatas[index].select;
//     setAllResDatas(_resDatas);
//   }
//   //全选
//   const  allCardDatas =()=>{
//     console.log('全选')
//     for(let ii of resDatas){
//       ii.select =!allSelect;
//     }
//     setAllSelect(!allSelect)
//     setAllResDatas(resDatas);
//   }
//   //总计
//   const changeCardMoney =useCallback(()=>{
//     console.log('总计')
//     let allMoney:number =0;
//     console.log(resDatas)
//     for(let ii of resDatas){
//       if(!!ii.select){
//         allMoney+=ii.money;
//       }
//     }
//     return allMoney
//   },[resDatas,allSelect])
//   return (
//     <div className='cart_main'>
//       <ul>
//         {resDatas.map((item,index)=>{
//           return (<li className='list_li'>
//             <CheckboxItem checked={item.select} key={item.name} 
//             onChange={()=>{changeCardDatas(index)}}></CheckboxItem>
//             <div className='li_name'>{item.name}</div>
//             <div className='li_money'>￥{Number(item.money).toFixed(2)}</div>
//           </li>)
//         })}
//         <li className='list_li'>
//           <CheckboxItem checked={allSelect} onChange={()=>{allCardDatas()}}></CheckboxItem>
//           <div className='li_name'>全选</div>
//           <div className='li_money'>￥{changeCardMoney()}</div>
//         </li>
//       </ul>
//     </div>
//   )
// }

//Cart 2.0
interface GoodDatas {
  name:string;
  money:number;
  select:boolean;
}
type SelectAction = {
  type:string;
  datas:GoodDatas
}
const Cart:React.FC<{}> = (props) => {
  const CheckboxItem = Checkbox.CheckboxItem;


  let [goodDatas,setGoodDatas] = useState([{select:false,name:'牛奶',money:100},
  {select:false,name:'面包',money:100},
  {select:false,name:'咖啡',money:100},
  {select:false,name:'手机',money:100},
  {select:false,name:'电脑',money:100},
  {select:false,name:'妹子',money:100}]);
  console.log('渲染了');
  let allSelect =useMemo(()=>{
    //是否全选
    let allSelect =true;
    for(let ii of goodDatas){
      if(!ii.select){
        allSelect =false;
      }
    }
    return allSelect;
  },[goodDatas])
  //单选
  let itemSelect = useCallback((goodItem:GoodDatas) => {
    var goodDatas1 = JSON.parse(JSON.stringify(goodDatas))
    let _goodDatas =goodDatas1.map((item:GoodDatas)=>{
      if(item.name==goodItem.name){
        return goodItem;
      }
      return item;
    })
    setGoodDatas(_goodDatas);
  },[goodDatas]);
  //全选
  let allSelectFun = () => {
    let _goodDatas = [...goodDatas]
    console.log(allSelect);
    for(let ii of _goodDatas){
      ii.select = !allSelect;
    }
    console.log(_goodDatas)
    setGoodDatas(_goodDatas);
  }
  
  //总价
  let allCardMoney = () => {
    let allMoney:number = 0;
    for(let ii of goodDatas){
      if(ii.select===true){
        allMoney += Number(ii.money);
      }
    }
    return allMoney;
  }
  return (
    <div className='cart_main'>
      <ul>
        {goodDatas.map((item:GoodDatas,index:number)=>{
          return (<CartItem  item={item} itemSelect={itemSelect}/>)
        })}
        <li className='list_li'>
          <CheckboxItem checked={allSelect} onChange={()=>{ allSelectFun()}}></CheckboxItem>
          <div className='li_name'>全选</div>
          <div className='li_money'>￥{allCardMoney()||0}</div>
        </li>
      </ul>
    </div>
  )
}
//判断是否渲染子组件
interface Props {
  item:GoodDatas;
  itemSelect:Function
}
//子组件
const CartItem:FC<Props> = React.memo((props)=>{
  const CheckboxItem = Checkbox.CheckboxItem;
  //子组件是否发生变化 防止没必要的渲染
  let { item,itemSelect } = props;
  return (
    <li className='list_li'>
      <CheckboxItem checked={item.select} key={item.name}
      onChange={()=>{itemSelect({...item,select:!item.select})}}></CheckboxItem>
      <div className='li_name'>{item.name}</div>
      <div className='li_money'>￥{Number(item.money).toFixed(2)}</div>
    </li>
  )
})

//将store里面的数据映射到props 这个数据
//就是取store的数据 然后操作 赋值给页面的变量
//将页面数据和全局数据绑定
const mapState = ({ store }: any) => {
  return ({
    isLogin: store.isLogin,
    userInfo:store.userInfo
  })
}

const mapDispatch = ({ store }: any) => ({
  // changeLoaderType() {
  //   store.changeLoaderType(true)
  // }
  setPlayListAct(data:any){
    store.setPlayListAct(data)
  },
  setMp3ListAct(data:any){
    store.setMp3ListFun(data)
  },
})
//返回了 connect 其实是一个容器组件
export default connect(mapState, mapDispatch)(Myinfo); 